import React, { useEffect, useMemo, useState } from "react"
import Taro from "@tarojs/taro"
import { AtIcon } from "taro-ui"
import { Image, Input, Text, View } from "@tarojs/components"
import "./index.scss"
import http from "../../utils/http"
import PriceDetail from "../../components/price-detail"
import phone2 from "../../assets/images/phone2.png"
import changeIcon from "../../assets/images/change.png"
import { statusData } from "../../common"
import { getUser } from "../../utils"
import Modal from "../../components/Modal"

export default function () {
  const [orderDetail, setOrderDetail] = useState({})
  const userInfo = getUser("userInfo")
  const isAdmin = userInfo?.role != 0
  const [showRemarkInput, setShowRemarkInput] = useState(false)
  const [showPriceList, setShowPriceList] = useState(false)
  const [configPrice, setConfigPrice] = useState(null)
  const [showModal, setShowModal] = useState(false)
  const [showPriceDetail, setShowPriceDetail] = useState(false)
  const getDetail = async () => {
    const ticketId = Taro.getCurrentInstance().router.params.id
    const { data } = await http.get(`/core/ticket/search/${ticketId}`)
    if (data) {
      setOrderDetail(data)
    }
    const { data: priceData } = await http.post("/core/config/data/search", { dictType: "EXTRA_CHARGE" })
    if (priceData?.EXTRA_CHARGE) {
      if (data.extra) {
        const extra = JSON.parse(data.extra)
        const selectList = priceData?.EXTRA_CHARGE.map(item => ({
          ...item,
          selected: !!extra.find(i => i.key === item.dictCode),
        }))
        setConfigPrice(selectList)
      } else {
        setConfigPrice(priceData?.EXTRA_CHARGE.map(i => ({ ...i, selected: false })))
      }
    }
  }

  const changeStatus = async status => {
    const { data } = await http.post("/core/ticket/update", {
      ticketId: orderDetail.ticketId,
      status,
    })
    if (data) {
      Taro.showToast({
        title: "操作成功",
        icon: "success",
      })
      getDetail()
    }
  }

  let statusBtn = ""
  switch (orderDetail.status) {
    case 0:
      if (!isAdmin) {
        statusBtn = (
          <>
            <View
              className="change-status"
              onClick={() => {
                Taro.navigateTo({ url: `/pages/appointment/index?id=${orderDetail.ticketId}` })
              }}
            >
              修改订单
            </View>
            <View
              className="change-status cancel"
              onClick={async () => {
                setShowModal("cancel")
              }}
            >
              取消预约单
            </View>
          </>
        )
      } else {
        statusBtn = (
          <>
            <View
              className="change-status"
              onClick={async () => {
                setShowModal("confirm")
              }}
            >
              确认
            </View>
            <View
              className="change-status cancel"
              onClick={async () => {
                setShowModal("cancel")
              }}
            >
              取消预约单
            </View>
          </>
        )
      }
      break
    case 1:
      if (!isAdmin) {
        statusBtn = (
          <View
            className="change-status"
            style={{ background: "#B32D2D" }}
            onClick={() => {
              Taro.showToast({
                title: "线上支付功能暂未开通，请联系场馆线下支付",
                icon: "none",
              })
            }}
          >
            去支付
          </View>
        )
      }
      break
    case 3:
      statusBtn = (
        <>
          <View className="change-status" onClick={() => setShowModal("take")}>
            确认取拍
          </View>
        </>
      )
  }

  const modalData = {
    confirm: {
      title: "确认接单",
      text: "确认接单后，系统将创建支付订单",
      text2: "如有疑问，请提前联系客户",
      confirmText: "确认接单",
      onConfirm: async () => {
        const params = {
          ticketId: orderDetail.ticketId,
          status: 1,
          price: Number(orderDetail.price),
          extra: orderDetail.extra,
          adminRemark: orderDetail.adminRemark,
        }
        await http.post("/core/ticket/update", params)
        Taro.showToast({
          title: "操作成功",
          icon: "success",
        })
        setShowModal(false)
        getDetail()
      },
    },
    cancel: {
      title: "取消订单",
      text: isAdmin ? "该订单为待支付订单，请与客户确认后再取消" : "该订单为预约单，是否确认取消",
      text2: "",
      confirmText: "确认取消",
      onConfirm: () => {
        changeStatus(5)
      },
    },
    take: {
      title: "确认取拍",
      text: "请在收到球拍后，验收相关物品，无误后点击确认取拍",
      text2: "",
      confirmText: "确认取拍",
      onConfirm: () => {
        changeStatus(4)
      },
    },
  }

  useEffect(() => {
    getDetail()
  }, [])

  const otherPriceStringLabel = useMemo(() => {
    const selectedPriceList = configPrice?.filter(item => {
      return item.selected > 0
    })
    if (selectedPriceList && selectedPriceList.length > 0) {
      return selectedPriceList.map(item => item.dictLabel).join(",")
    } else {
      return "暂无"
    }
  }, [configPrice])

  return (
    <View className="page-appointment-order-detail">
      <View className="row">
        <View className="label">预约单号</View>
        <View className="value">{orderDetail.ticketId}</View>
      </View>
      <View className="row">
        <View className="label">状态</View>
        <View className="value">{statusData[orderDetail.status]?.name}</View>
      </View>
      <View className="row">
        <View className="label">下单时间</View>
        <View className="value">{orderDetail.createdAt}</View>
      </View>
      <View className="row">
        <View className="label">姓名</View>
        <View className="value">{orderDetail.userName}</View>
      </View>
      <View className="row">
        <View className="label">手机号码</View>
        {!isAdmin ? (
          <View className="value">{orderDetail.phone}</View>
        ) : (
          <View
            className="value"
            onClick={() =>
              Taro.makePhoneCall({
                phoneNumber: orderDetail.phone,
              })
            }
          >
            <View style={{ color: "#2E6BB9" }}>{orderDetail.phone}</View>
            <Image src={phone2}></Image>
          </View>
        )}
      </View>
      <View className="row">
        <View className="label">球拍品牌</View>
        <View className="value">{orderDetail.racketBrand}</View>
      </View>
      <View className="row">
        <View className="label">穿线类型</View>
        <View className="value">{orderDetail.threadingType}</View>
      </View>
      {orderDetail.linePrice > 0 && (
        <View className="row">
          <View className="label">线型号</View>
          <View className="value">{orderDetail.lineType}</View>
        </View>
      )}
      <View className="row">
        <View className="label">磅数</View>
        <View className="value">{orderDetail.linePound}</View>
      </View>

      {!isAdmin ? (
        <View className="row">
          <View className="label">备注</View>
          <View className="value">{orderDetail.userRemark || <Text style={{ color: "#aaaaaa" }}>暂无备注</Text>}</View>
        </View>
      ) : (
        <>
          <View className="row">
            <View className="label">用户备注</View>
            <View className="value">
              {orderDetail.userRemark || <Text style={{ color: "#aaaaaa" }}>暂无备注</Text>}
            </View>
          </View>
          <View className="row">
            <View className="label">管理备注</View>
            <View className="value">
              {showRemarkInput ? (
                <Input
                  focus={showRemarkInput}
                  value={orderDetail.adminRemark}
                  onInput={e =>
                    setOrderDetail({
                      ...orderDetail,
                      adminRemark: e.detail.value,
                    })
                  }
                  onBlur={() => {
                    setShowRemarkInput(false)
                  }}
                ></Input>
              ) : (
                <>
                  {orderDetail.adminRemark}
                  <Image src={changeIcon} onClick={() => setShowRemarkInput(true)}></Image>
                </>
              )}
            </View>
          </View>
        </>
      )}
      {!isAdmin && (
        <View className="row">
          <View className="label">取拍时间</View>
          <View className="value">{orderDetail.takeRacketTime}</View>
        </View>
      )}
      {isAdmin && (
        <View className="row">
          <View className="label">附加项</View>
          <View className="value">
            <View className="add-price" onClick={() => setShowPriceList(!showPriceList)}>
              <View className="add-price-text">{otherPriceStringLabel}</View>
              <AtIcon value={showPriceList ? "chevron-up" : "chevron-down"}></AtIcon>
            </View>
            {showPriceList && (
              <View className="add-price-list">
                {configPrice &&
                  configPrice.map(item => {
                    return (
                      <View className="add-price-item" key={item.dictCode}>
                        <View className="add-price-item-name">{item.dictLabel}</View>
                        <View
                          className={`add-price-item-check ${item.selected ? "active" : ""}`}
                          onClick={() => {
                            item.selected = !item.selected
                            setConfigPrice([...configPrice])
                            const selectedList = configPrice.filter(i => i.selected)
                            let selectedReducePrice = 0
                            selectedList.forEach(i => {
                              if (i.selected) {
                                selectedReducePrice = selectedReducePrice + Number(i.dictValue)
                              }
                            })
                            setOrderDetail({
                              ...orderDetail,
                              price: (selectedReducePrice + orderDetail.linePrice).toFixed(0),
                              extra: JSON.stringify(
                                selectedList.map(i => {
                                  return { key: i.dictCode, name: i.dictLabel, value: Number(i.dictValue) }
                                })
                              ),
                            })
                          }}
                        >
                          {item.selected && <AtIcon value="check"></AtIcon>}
                        </View>
                      </View>
                    )
                  })}
              </View>
            )}
          </View>
        </View>
      )}
      <View className="row">
        <View className="label">{!isAdmin ? "预计费用" : "订单金额"}</View>
        <View className="value">¥{orderDetail.price}</View>
        {}
        <View className="price-show-detail" onClick={() => setShowPriceDetail(!showPriceDetail)}>
          <PriceDetail
            show={showPriceDetail}
            productPrice={orderDetail.linePrice}
            otherPrice={orderDetail.extra ? JSON.parse(orderDetail.extra) : null}
          ></PriceDetail>
          明细
        </View>
      </View>
      {statusBtn && <View className="btns">{statusBtn}</View>}
      {(showPriceList || showPriceDetail) && (
        <View
          className="price-detail-mask"
          onClick={() => {
            setShowPriceList(false)
            setShowPriceDetail(false)
          }}
        ></View>
      )}

      <Modal
        isOpened={showModal}
        titleText={modalData[showModal]?.title}
        cancelText="取消"
        onCancel={() => setShowModal(false)}
        onConfirm={() => modalData[showModal]?.onConfirm()}
        confirmText={modalData[showModal]?.confirmText}
      >
        <View className="modal-text">
          <View>{modalData[showModal]?.text}</View>
          <View>{modalData[showModal]?.text2}</View>
        </View>
      </Modal>
    </View>
  )
}
